﻿using Learun.Util;
using Learun.Util.SqlSugar;
using log4net.Config;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Controls.Primitives;
using DbType = System.Data.DbType;

namespace Learun.Application.TwoDevelopment.ZZDT_EC
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2022-03-07 13:44
    /// 描 述：工程数据表
    /// </summary>
    public class ec_enginedataService
    {
        #region 仓储
        Repository<ec_projectEntity> _projectRepository => new Repository<ec_projectEntity>();
        Repository<ec_enginedataEntity> _enginedataRepository => new Repository<ec_enginedataEntity>();
        Repository<ec_enginedata_pixelEntity> _enginedataPixelRepository => new Repository<ec_enginedata_pixelEntity>();
        Repository<ec_enginedata_propertyEntity> _enginedataPropertyRepository => new Repository<ec_enginedata_propertyEntity>();
        Repository<ec_enginedata_propertyhisEntity> _enginedataPropertyhisRepository => new Repository<ec_enginedata_propertyhisEntity>();
        Repository<ec_enginedata_relEntity> _enginedataRelRepository => new Repository<ec_enginedata_relEntity>();
        Repository<ec_PanelEntity> _panelRepository => new Repository<ec_PanelEntity>();
        Repository<ec_propertyEntity> _propertyRepository => new Repository<ec_propertyEntity>();
        Repository<ec_CaseEntity> _caseRepository => new Repository<ec_CaseEntity>();
        #endregion
        #region 获取数据
        /// <summary>
        /// 获取回收站页面显示列表数据
        /// <summary>
        /// <param name="queryJson">查询参数</param>
        /// <returns></returns>
        public IEnumerable<ec_enginedataEntity> GetRecycleBinPageList(Pagination pagination, string queryJson)
        {
            try
            {
                var ProjectEntity = new ec_projectEntity();
                var queryParam = queryJson.ToJObject();
                var strSql = new StringBuilder();
                strSql.Append("SELECT t1.*, t2.ObjectTypeName, t2.FullPathCN, t3.F_ItemName AS DataStatusName ");
                if (queryParam["ProjectId"].IsEmpty())
                {
                    strSql.Append("  FROM ec_enginedata t1 ");
                    strSql.Append("  LEFT JOIN ec_objecttype t2 ON t1.ObjectTypeID = t2.ObjectTypeID ");
                }
                else
                {
                    //ProjectEntity = this.BaseRepository().FindEntity<ec_projectEntity>(queryParam["ProjectId"].ToString());
                    ProjectEntity = _projectRepository.GetById(queryParam["ProjectId"].ToString());
                    strSql.Append($"  FROM ec_enginedata_{ProjectEntity.ProjectIndex} t1 ");
                    strSql.Append($"  LEFT JOIN ec_objecttype_{ProjectEntity.ProjectIndex} t2 ON t1.ObjectTypeID = t2.ObjectTypeID ");
                }
                strSql.Append(@" 
                            LEFT JOIN lr_base_dataitemdetail t3 ON t3.F_ItemValue = t1.DataStatus AND t3.F_ItemId IN (SELECT st1.F_ItemId FROM LR_Base_DataItem st1 WHERE st1.F_ItemCode= 'Be_DataStatus')
                            WHERE t1.DataStatus != '00001' ");
                if (queryParam["ProjectId"].IsEmpty())
                {
                    strSql.Append(" AND (select count(1) from ec_enginedata_pixel st2 where st2.EngineDataID = t1.EngineDataID) = 0  ");
                }
                else
                {
                    strSql.Append($"  AND (select count(1) from ec_enginedata_pixel_{ProjectEntity.ProjectIndex} st2 where st2.EngineDataID = t1.EngineDataID) = 0 ");
                }
                // 虚拟参数

                //var dp = new DynamicParameters(new { });
                var dp = new List<SugarParameter>();
                if (!queryParam["TagNumber"].IsEmpty())
                {
                    dp.Add(new SugarParameter("TagNumber", "%" + queryParam["TagNumber"].ToString() + "%", DbType.String));
                    strSql.Append(" AND t1.TagNumber Like @TagNumber ");
                }
                if (!queryParam["UpObjectTypeID"].IsEmpty())
                {
                    dp.Add(new SugarParameter("UpObjectTypeID", "%" + queryParam["UpObjectTypeID"].ToString() + "%", DbType.String));
                    strSql.Append(" AND t2.FullPath LIKE @UpObjectTypeID ");
                }
                if (!queryParam["DataStatus"].IsEmpty())
                {
                    dp.Add(new SugarParameter("DataStatus", queryParam["DataStatus"].ToString(), DbType.String));
                    strSql.Append(" AND t1.DataStatus = @DataStatus ");
                }
                //return this.BaseRepository().FindList<ec_enginedataEntity>(strSql.ToString(), dp, pagination);
                return SqlSugarHelper.Db.SqlQueryable<ec_enginedataEntity>(strSql.ToString()).AddParameters(dp).ToPageList(pagination.page, pagination.rows);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }
        /// <summary>
        /// 查询单表
        /// </summary>
        /// <param name="projId"></param>
        /// <param name="IDs"></param>
        /// <returns></returns>
        public List<ec_enginedataEntity> GetListSingleTable(string projId, List<string> IDs)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(projId))
                {
                    return null;
                }
                else
                {
                    var tableName = ProjectSugar.TableName<ec_enginedataEntity>(projId);
                    //var strSql = new StringBuilder();
                    //strSql.Append($@"SELECT * FROM ec_enginedata_{ProjectEntity.ProjectIndex} WHERE EngineDataID = @EngineDataID ");
                    //List<ec_enginedataEntity> list = this.BaseRepository().FindList<ec_enginedataEntity>(strSql.ToString(), new { EngineDataID = keyValue }).ToList();
                    //return list.FirstOrDefault();
                    var res = SqlSugarHelper.Db.Queryable<ec_enginedataEntity>().AS(tableName)
                        .WhereIF(IDs != null && IDs.Count > 0, x => IDs.Contains(x.EngineDataID))
                        .ToList();
                    return res;
                }

            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 根据enginedata 属性 objectType 去找。By Yuxingheng
        /// </summary>
        /// <param name="sqlWhere"></param>
        /// <param name="projId"></param>
        /// <returns></returns>
        public IEnumerable<ec_enginedataEntity> GetListBySQL(string sqlWhere, string projId)
        {
            string strSql = "";
            if (projId != "0")
            {

                //var ProjectEntity = this.BaseRepository().FindEntity<ec_projectEntity>(projId);
                var ProjectEntity = _projectRepository.GetById(projId);
                if (ProjectEntity != null)
                {
                    //原来的列：TagNumber,t.SerialNumber,t.ObjectTypeID,t.EngineDataID
                    strSql = $"SELECT DISTINCT t.*,t3.ObjectTypeName,t3.ObjectTypeNameEN " +
                        $"FROM ec_enginedata_{ProjectEntity.ProjectIndex} t " +
                        $"left join ec_enginedata_property_{ProjectEntity.ProjectIndex} t2 on t.EngineDataID=t2.EngineDataID " +
                        $"join ec_objecttype_{ProjectEntity.ProjectIndex} t3 on t3.ObjectTypeID=t.ObjectTypeID ";
                    if (sqlWhere.Trim() == "")
                    {

                    }
                    else
                    {
                        strSql += " where " + sqlWhere;
                    }

                }

            }
            //return this.BaseRepository().FindList<ec_enginedataEntity>(strSql);
            return SqlSugarHelper.Db.SqlQueryable<ec_enginedataEntity>(strSql.ToString()).ToList();
        }
        /// <summary>
        /// 获取实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public ec_enginedataEntity GetEntity(string keyValue, string ProjectId)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(ProjectId))
                {
                    return _enginedataRepository.GetById(keyValue);
                }
                else
                {
                    var ProjectEntity = _projectRepository.GetById(ProjectId);
                    var strSql = new StringBuilder();
                    strSql.Append($@"SELECT * FROM ec_enginedata_{ProjectEntity.ProjectIndex} WHERE EngineDataID = @EngineDataID ");
                    //List<ec_enginedataEntity> list = this.BaseRepository().FindList<ec_enginedataEntity>(strSql.ToString(), new { EngineDataID = keyValue }).ToList();
                    //return list.FirstOrDefault();
                    return SqlSugarHelper.Db.Ado.SqlQuerySingle<ec_enginedataEntity>(strSql.ToString(), new { EngineDataID = keyValue });
                }

            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 获取记录条数
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public int GetDataCount(string ProjectId)
        {
            try
            {
                var ProjectEntity = _projectRepository.GetById(ProjectId);
                var strSql = new StringBuilder();
                if (string.IsNullOrWhiteSpace(ProjectId))
                {
                    strSql.Append($@"SELECT COUNT(1) FROM ec_enginedata ");
                }
                else
                {

                    strSql.Append($@"SELECT COUNT(1) FROM ec_enginedata_{ProjectEntity.ProjectIndex} ");
                }
                //int count = this.BaseRepository().FindObject(strSql.ToString()).ToInt();
                int count = SqlSugarHelper.Db.Ado.GetInt(strSql.ToString());
                return count;
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        #endregion

        #region 提交数据

        /// <summary>
        /// 删除实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void DeleteEntity(string keyValue, string ProjectId)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                if (string.IsNullOrWhiteSpace(ProjectId))
                {
                    _enginedataRepository.Delete(t => t.EngineDataID == keyValue);
                    _enginedataPixelRepository.Delete(t => t.EngineDataID == keyValue);
                    _enginedataPropertyRepository.Delete(t => t.EngineDataID == keyValue);
                    _enginedataPropertyhisRepository.Delete(t => t.EngineDataID == keyValue);
                    _enginedataRelRepository.Delete(t => t.RelEngineData1ID == keyValue || t.RelEngineData2ID == keyValue);
                }
                else
                {
                    var ProjectEntity = _projectRepository.GetById(ProjectId);
                    //追加
                    ec_PanelBLL ec_PanelBLL = new ec_PanelBLL();
                    var panels = ec_PanelBLL.GetList("{ProjectId:\"" + ProjectEntity.ProjectId + "\"}");
                    var panel = panels.FirstOrDefault(x => x.EngineerDataID == keyValue);

                    SqlSugarHelper.Db.Ado.ExecuteCommand($@" DELETE FROM ec_enginedata_{ProjectEntity.ProjectIndex} WHERE EngineDataID = '{keyValue}';
                               DELETE FROM ec_enginedata_pixel_{ProjectEntity.ProjectIndex} WHERE EngineDataID = '{keyValue}';
                               DELETE FROM ec_enginedata_property_{ProjectEntity.ProjectIndex} WHERE EngineDataID = '{keyValue}'; 
                               DELETE FROM ec_enginedata_propertyhis_{ProjectEntity.ProjectIndex} WHERE EngineDataID = '{keyValue}'; 
                               DELETE FROM ec_enginedata_rel_{ProjectEntity.ProjectIndex} WHERE RelEngineData1ID = '{keyValue}' OR RelEngineData2ID ='{keyValue}'; 
                               ");
                    if (panel != null)
                    {
                        SqlSugarHelper.Db.Ado.ExecuteCommand($@" DELETE FROM ec_panel_{ProjectEntity.ProjectIndex} WHERE EngineerDataID = '{keyValue}'");
                        SqlSugarHelper.Db.Ado.ExecuteCommand($@" DELETE FROM ec_panel_strip_{ProjectEntity.ProjectIndex} WHERE PanelID = '{panel.PanelID}'");
                        SqlSugarHelper.Db.Ado.ExecuteCommand($@" DELETE FROM ec_panel_strip_term_{ProjectEntity.ProjectIndex} WHERE PanelID = '{panel.PanelID}'");
                        SqlSugarHelper.Db.Ado.ExecuteCommand($@" DELETE FROM ec_panel_channel_{ProjectEntity.ProjectIndex} WHERE PanelID = '{panel.PanelID}'");
                        SqlSugarHelper.Db.Ado.ExecuteCommand($@" DELETE FROM ec_wire_terminal_{ProjectEntity.ProjectIndex} WHERE PanelID = '{panel.PanelID}'");
                    }

                }
                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void SaveEntity(string keyValue, ec_enginedataEntity entity, string ProjectId)
        {
            if (string.IsNullOrEmpty(entity.CaseID))
            {
                entity.CaseID = "0";
            }
            try
            {
                if (!string.IsNullOrEmpty(keyValue))
                {
                    entity.Modify(keyValue);
                    if (string.IsNullOrWhiteSpace(ProjectId))
                    {
                        _enginedataRepository.Update(entity);
                    }
                    else
                    {
                        var ProjectEntity = _projectRepository.GetById(ProjectId);
                        _enginedataRepository.AsUpdateable(entity).AS($"ec_enginedata_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                    }
                }
                else
                {
                    entity.Create();
                    if (string.IsNullOrWhiteSpace(ProjectId))
                    {
                        _enginedataRepository.Insert(entity);
                    }
                    else
                    {
                        var ProjectEntity = _projectRepository.GetById(ProjectId);
                        _enginedataRepository.AsInsertable(entity).AS($"ec_enginedata_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                        var objectType = new ec_objecttypeBLL().GetEntity(entity.ObjectTypeID, ProjectId);
                        if (objectType != null && objectType.SystemPanel == 1)
                        {
                            //如果对象类型属于特定的panel类 
                            var newPanel = new ec_PanelEntity();
                            newPanel.Create();
                            newPanel.EngineerDataID = entity.EngineDataID;

                            new ec_PanelBLL().SaveEntity(ProjectId, "", newPanel);
                        }
                    }
                    //工程数据位号工况和属性默认值
                    var caseTableName = ProjectSugar.TableName<ec_CaseEntity>(ProjectId);
                    //var caseEntity = new ec_CaseEntity()
                    //{
                    //    EngineDataID = entity.EngineDataID,
                    //    CaseName = entity.TagNumber,
                    //    IsActive = "1"
                    //};
                    //caseEntity.Create();
                    //_caseRepository.AsInsertable(caseEntity).AS(caseTableName).ExecuteCommand();
                    var cases = _caseRepository.AsQueryable().AS(caseTableName).ToList();

                    var propertyTableName = ProjectSugar.TableName<ec_propertyEntity>(ProjectId);
                    var objecttypepTableName = ProjectSugar.TableName<ec_objecttypepEntity>(ProjectId);
                    var objecttypeTableName = ProjectSugar.TableName<ec_objecttypeEntity>(ProjectId);
                    var unitTableName = ProjectSugar.TableName<ec_measuring_unitEntity>(ProjectId);
                    var enginedataPropTableName = ProjectSugar.TableName<ec_enginedata_propertyEntity>(ProjectId);


                    foreach (ec_CaseEntity caseEntity in cases)
                    {
                        var enginedataProps = new List<ec_enginedata_propertyEntity>();
                        _propertyRepository.AsQueryable().AS(propertyTableName)
                            .InnerJoin<ec_objecttypepEntity>((a, b) => a.PropertyID == b.PropertyID)//&& !string.IsNullOrEmpty(a.DefaultValue)
                            .AS<ec_objecttypepEntity>(objecttypepTableName)
                            .InnerJoin<ec_objecttypeEntity>((a, b, c) => b.ObjectTypeID == c.ObjectTypeID && c.ObjectTypeID == entity.ObjectTypeID)
                            .AS<ec_objecttypeEntity>(objecttypeTableName)
                            .LeftJoin<ec_measuring_unitEntity>((a, b, c, d) => a.DefaultUnit == d.MeasuringUnitID)
                            .AS<ec_measuring_unitEntity>(unitTableName)
                            .Select((a, b, c, d) => new { a, d })
                            .ToList().ForEach(x =>
                            {
                                var enginedataProp = new ec_enginedata_propertyEntity()
                                {
                                    EngineDataID = entity.EngineDataID,
                                    PropertyName = x.a.PropertyName,
                                    PropertyValue = x.a.DefaultValue,
                                    MeasuringUnit = x.d.MeasuringUnitName,
                                    CaseID = caseEntity.CaseID,
                                };
                                enginedataProp.Create();
                                enginedataProps.Add(enginedataProp);
                            });
                        _enginedataPropertyRepository.AsInsertable(enginedataProps).AS(enginedataPropTableName).ExecuteCommand();
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 批量保存导入的工程数据、属性(更新的case为0）
        /// <summary>
        /// <returns></returns>
        public void SaveImportData(List<ec_enginedataEntity> entityList, string ProjectId)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                var ProjectEntity = _projectRepository.GetById(ProjectId);
                //要新增的工程数据属性历史数据集合
                List<ec_enginedata_propertyhisEntity> engineDataPropHis = new List<ec_enginedata_propertyhisEntity>();
                //获取当前项目的所有工程数据属性
                var _TagPropRepository = new Repository<ec_enginedata_propertyEntity>();
                var allEngineProp = _TagPropRepository.AsQueryable().AS($"ec_enginedata_property_{ProjectEntity.ProjectIndex}").
                    Where(x => (x.CaseID == "0" || string.IsNullOrEmpty(x.CaseID))).ToList();
                if (string.IsNullOrWhiteSpace(ProjectId))
                {
                    List<ec_enginedataEntity> addEngineData = new List<ec_enginedataEntity>();
                    List<ec_enginedataEntity> updateEngineData = new List<ec_enginedataEntity>();
                    List<ec_enginedata_propertyEntity> addEnginePropData = new List<ec_enginedata_propertyEntity>();
                    List<ec_enginedata_propertyEntity> updateEnginePropData = new List<ec_enginedata_propertyEntity>();
                    List<ec_PanelEntity> addPanel = new List<ec_PanelEntity>();
                    foreach (var item in entityList)
                    {
                        if (string.IsNullOrEmpty(item.EngineDataID))
                        {
                            //新增位号
                            item.Create();
                            item.DataStatus = "00001";
                            item.CaseID = "0";

                            addEngineData.Add(item);
                            foreach (var it in item.EngineDataProperty)
                            {
                                it.Create();
                                it.EngineDataID = item.EngineDataID;
                                item.CaseID = "0";
                                addEnginePropData.Add(it);
                            }

                            var objectType = new ec_objecttypeBLL().GetEntity(item.ObjectTypeID, ProjectId);
                            if (objectType != null && objectType.SystemPanel == 1)
                            {
                                //如果对象类型属于特定的panel类 
                                var newPanel = new ec_PanelEntity();
                                newPanel.Create();
                                newPanel.EngineerDataID = item.EngineDataID;

                                addPanel.Add(newPanel);
                            }
                        }
                        else
                        {
                            //更新位号
                            item.Modify(item.EngineDataID);
                            updateEngineData.Add(item);
                            foreach (var it in item.EngineDataProperty)
                            {
                                var temEngineProp = allEngineProp.Find(x => x.PropertyName == it.PropertyName && x.EngineDataID == item.EngineDataID);
                                if (temEngineProp != null)
                                {
                                    it.Modify(temEngineProp.EngineDataPropertyID);
                                    it.EngineDataID = item.EngineDataID;
                                    it.CaseID = item.CaseID;
                                    updateEnginePropData.Add(it);

                                    ec_enginedata_propertyhisEntity modelHis = new ec_enginedata_propertyhisEntity();
                                    modelHis.EngineDataID = item.EngineDataID;
                                    modelHis.PropertyName = it.PropertyName;
                                    modelHis.PropertyValue = temEngineProp.PropertyValue;
                                    modelHis.Create();
                                    engineDataPropHis.Add(modelHis);
                                }
                                else
                                {
                                    it.Create();
                                    it.EngineDataID = item.EngineDataID;
                                    it.CaseID = item.CaseID;
                                    addEnginePropData.Add(it);
                                }
                            }
                        }
                    }
                    _enginedataRepository.InsertRange(addEngineData);
                    _enginedataRepository.UpdateRange(updateEngineData);
                    _enginedataPropertyRepository.InsertRange(addEnginePropData);
                    _enginedataPropertyRepository.UpdateRange(updateEnginePropData);
                    _enginedataPropertyhisRepository.InsertRange(engineDataPropHis);
                    _panelRepository.InsertRange(addPanel);
                }
                else
                {

                    foreach (var item in entityList)
                    {
                        if (string.IsNullOrEmpty(item.EngineDataID))
                        {
                            //新增位号
                            item.Create();
                            item.DataStatus = "00001";
                            //db.InsertByNoMap(item, $"ec_enginedata_{ProjectEntity.ProjectIndex}");
                            _enginedataRepository.AsInsertable(item).AS($"ec_enginedata_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                            foreach (var it in item.EngineDataProperty)
                            {
                                it.Create();
                                it.EngineDataID = item.EngineDataID;
                                it.CaseID = "0";
                                //db.InsertByNoMap(it, $"ec_enginedata_property_{ProjectEntity.ProjectIndex}");
                                _enginedataPropertyRepository.AsInsertable(it).AS($"ec_enginedata_property_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                            }
                        }
                        else
                        {
                            //更新位号
                            item.Modify(item.EngineDataID);
                            //db.UpdateByNoMap(item, $"ec_enginedata_{ProjectEntity.ProjectIndex}", "EngineDataID");
                            _enginedataRepository.AsUpdateable(item).AS($"ec_enginedata_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                            foreach (var it in item.EngineDataProperty)
                            {
                                var temEngineProp = allEngineProp.Find(x => (x.CaseID == "0" || string.IsNullOrEmpty(x.CaseID)) && x.PropertyName == it.PropertyName && x.EngineDataID == item.EngineDataID);
                                if (temEngineProp != null)
                                {
                                    it.Modify(temEngineProp.EngineDataPropertyID);

                                    it.EngineDataID = item.EngineDataID;
                                    it.CaseID = "0";

                                    ec_enginedata_propertyhisEntity modelHis = new ec_enginedata_propertyhisEntity();
                                    modelHis.EngineDataID = item.EngineDataID;
                                    modelHis.PropertyName = it.PropertyName;
                                    modelHis.PropertyValue = temEngineProp.PropertyValue;
                                    modelHis.CaseID = "0";
                                    modelHis.Create();
                                    engineDataPropHis.Add(modelHis);

                                    //db.UpdateByNoMap(it, $"ec_enginedata_property_{ProjectEntity.ProjectIndex}", "EngineDataPropertyID");
                                    _enginedataPropertyRepository.AsUpdateable(it).AS($"ec_enginedata_property_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                                }
                                else
                                {
                                    it.Create();
                                    it.EngineDataID = item.EngineDataID;
                                    it.CaseID = "0";
                                    //db.InsertByNoMap(it, $"ec_enginedata_property_{ProjectEntity.ProjectIndex}");
                                    _enginedataPropertyRepository.AsInsertable(it).AS($"ec_enginedata_property_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                                }
                            }
                        }

                    }
                    //db.InsertByNoMap(engineDataPropHis, $"ec_enginedata_propertyhis_{ProjectEntity.ProjectIndex}");
                    _enginedataPropertyhisRepository.AsInsertable(engineDataPropHis).AS($"ec_enginedata_propertyhis_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                }
                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 批量修改数据状态
        /// <summary>
        /// <returns></returns>
        public void UpdateDataStatus(List<ec_enginedataEntity> entityList, string ProjectId)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                if (string.IsNullOrWhiteSpace(ProjectId))
                {
                    foreach (var item in entityList)
                    {
                        item.Modify(item.EngineDataID);
                        item.DataStatus = "00003";
                    }
                    _enginedataRepository.UpdateRange(entityList);
                }
                else
                {
                    var ProjectEntity = _projectRepository.GetById(ProjectId);
                    foreach (var item in entityList)
                    {
                        item.Modify(item.EngineDataID);
                        item.DataStatus = "00003";
                        //db.UpdateByNoMap(item, $"ec_enginedata_{ProjectEntity.ProjectIndex}", "EngineDataID");
                        _enginedataRepository.AsUpdateable(item).AS($"ec_enginedata_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                    }
                }
                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 对象浏览器修改位号
        /// </summary>
        /// <param name="ProjectId">项目ID</param>
        /// <param name="updataEnginedata">要更新的工程数据实体</param>
        /// <param name="delEngineDataID">要删除的工程数据属性表、工程数据表数据对应的工程数据ID</param>
        /// <param name="updataEngineDataPixel">要更新的工程数据图元集合</param>
        /// <param name="updataEngineDataProp">要更新的工程数据属性集合</param>
        /// <param name="addEngineDataProp">要新增的工程数据属性集合</param>
        public void UpdateTagNumber(string ProjectId, ec_enginedataEntity updataEnginedata, string delEngineDataID, List<ec_enginedata_pixelEntity> updataEngineDataPixel, List<ec_enginedata_propertyEntity> updataEngineDataProp, List<ec_enginedata_propertyEntity> addEngineDataProp, List<ec_enginedata_propertyhisEntity> engineDataPropHis)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                ec_projectEntity ProjectEntity = new ec_projectEntity();
                if (string.IsNullOrWhiteSpace(ProjectId))
                {
                    if (string.IsNullOrWhiteSpace(delEngineDataID))
                    {
                        _enginedataRepository.Update(updataEnginedata);
                    }
                    else
                    {
                        //删除对应的工程数据属性表、工程数据表数据
                        _enginedataPropertyRepository.Delete(t => t.EngineDataID == delEngineDataID);
                        _enginedataRepository.Delete(t => t.EngineDataID == delEngineDataID);
                        _enginedataPixelRepository.UpdateRange(updataEngineDataPixel);
                        _enginedataPropertyRepository.UpdateRange(updataEngineDataProp);
                        _enginedataPropertyRepository.InsertRange(addEngineDataProp);
                        _enginedataPropertyhisRepository.InsertRange(engineDataPropHis);
                    }
                    //db.ExecuteBySql(@"UPDATE ec_enginedata T1
                    //                    SET DataStatus = '00002'
                    //                    WHERE (SELECT COUNT(*) FROM ec_enginedata_pixel WHERE EngineDataID = T1.EngineDataID ) > 0 AND DataStatus != '00003'");
                }
                else
                {
                    ProjectEntity = _projectRepository.GetById(ProjectId);
                    if (string.IsNullOrWhiteSpace(delEngineDataID))
                    {
                        //db.UpdateByNoMap(updataEnginedata, $"ec_enginedata_{ProjectEntity.ProjectIndex}", "EngineDataID");
                        _enginedataRepository.AsUpdateable(updataEnginedata).AS($"ec_enginedata_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                    }
                    else
                    {
                        //删除对应的工程数据属性表、工程数据表数据
                        SqlSugarHelper.Db.Ado.ExecuteCommand($@" DELETE FROM ec_enginedata_property_{ProjectEntity.ProjectIndex} WHERE EngineDataID = '{delEngineDataID}';
                                            DELETE FROM ec_enginedata_{ProjectEntity.ProjectIndex} WHERE EngineDataID = '{delEngineDataID}';
                                        ");
                        //db.UpdateByNoMap(updataEngineDataPixel, $"ec_enginedata_pixel_{ProjectEntity.ProjectIndex}", "EngineDataPixelID");
                        //db.UpdateByNoMap(updataEngineDataProp, $"ec_enginedata_property_{ProjectEntity.ProjectIndex}", "EngineDataPropertyID");
                        //db.InsertByNoMap(addEngineDataProp, $"ec_enginedata_property_{ProjectEntity.ProjectIndex}");
                        //db.InsertByNoMap(engineDataPropHis, $"ec_enginedata_propertyhis_{ProjectEntity.ProjectIndex}");
                        _enginedataPixelRepository.AsUpdateable(updataEngineDataPixel).AS($"ec_enginedata_pixel_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                        _enginedataPropertyRepository.AsUpdateable(updataEngineDataProp).AS($"ec_enginedata_property_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                        _enginedataPropertyRepository.AsInsertable(addEngineDataProp).AS($"ec_enginedata_property_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                        _enginedataPropertyhisRepository.AsInsertable(engineDataPropHis).AS($"ec_enginedata_propertyhis_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                    }
                    //db.ExecuteBySql($@"UPDATE ec_enginedata_{ProjectEntity.ProjectIndex} T1
                    //                    SET DataStatus = '00002'
                    //                    WHERE (SELECT COUNT(*) FROM ec_enginedata_pixel_{ProjectEntity.ProjectIndex} WHERE EngineDataID = T1.EngineDataID ) > 0 AND DataStatus != '00003'");
                }
                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 图元属性修改
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="entity">工程数据实体</param>
        /// <param name="caseID">需要更新的属性的工况ID</param>
        public void UpdatePixelAndProp(string projectId, ec_enginedataEntity entity, string caseID = "")
        {

        }
        /// <summary>
        /// 更新工程数据属性默认值
        /// </summary>
        public void UpdateEngineDataByDefaultValue()
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                ;
                SqlSugarHelper.Db.CommitTran();

            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();

                XmlConfigurator.Configure();
                var log = log4net.LogManager.GetLogger("Error"); //参数就是config里logger节点的名字
                log.Error($"UpdatePixelAndProp,具体错误为：{ex.StackTrace}");
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }
        #endregion
    }
}
